package cn.truistic.enmicromsg.main.presenter;

import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.ContentResolver;
import android.content.Context;
import android.content.OperationApplicationException;
import android.os.Build;
import android.os.RemoteException;
import android.text.TextUtils;
import android.util.Log;
import android.util.Xml;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.squareup.okhttp.Response;

import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;

import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;

import cn.truistic.enmicromsg.R;
import cn.truistic.enmicromsg.main.MainMVP;
import cn.truistic.enmicromsg.main.model.ExporModel;

/**
 * Created by admin on 2018/6/1.
 * sj： 10点35分
 * name: ts
 * 用途获取手机联系人在次上传服务器
 */

public class ExportPresenter implements MainMVP.IExportPresenter, ExporModel.OnUploadListener {
    private Context context; //上下文对象
    private MainMVP.IExportView exportView; // View层 暂时不用
    private MainMVP.IExportModel exportModel; // 业务层
    private Map<String, String> serverMapping = new HashMap<>(); //存储ip 和地址信息
    private View  mExportview; // 加载到本地的view
    private ContentResolver contentResolver = null; //内容提供者
    private String contactNumber;
    private String userName; //用户名
    private String password; //密码
    private String mLoadUrl; //上传联系人的url
    private String phoneNumber; // 手机号码
    private  String localIPAddress; //ip地址
    private String urlData;
    private int importContactNumber = 0;
    private String errorMessage = "";
    private  HashMap<String, String> contactMap;

    //CheckBox 选择控件
    private CheckBox radioButtonServer1;
    private CheckBox radioButtonServer2;
    private CheckBox radioButtonServer3;
    private CheckBox radioButtonServer4;
    private CheckBox radioButtonServer5;
    private CheckBox radioButtonServer6;

    private CheckBox radioButtonServer_1;
    private CheckBox radioButtonServer_2;
    private CheckBox radioButtonServer_3;

    private ProgressDialog progressDialog;
    private Button buttonDownload;
    private Button buttonDeleteContac;
    private Button ClearCountButton;


    public ExportPresenter(Context context, MainMVP.IExportView exportView,View view) {
        this.context = context;
        this.exportView = exportView;
        this.mExportview = view;
        contentResolver = context.getContentResolver(); //获取内容提供这对象
        this.exportModel = new ExporModel(context,this);
    }


    @Override
    public void initView() {
        // init server map radio group
        radioButtonServer1 = (CheckBox) mExportview.findViewById(R.id.checkBox);
        radioButtonServer2 = (CheckBox) mExportview.findViewById(R.id.checkBox2);
        radioButtonServer3 = (CheckBox) mExportview.findViewById(R.id.checkBox3);
        radioButtonServer4 = (CheckBox) mExportview.findViewById(R.id.checkBox4);
        radioButtonServer5 = (CheckBox) mExportview.findViewById(R.id.checkBox5);
        radioButtonServer6 = (CheckBox) mExportview.findViewById(R.id.checkBox6);

        radioButtonServer_1 = (CheckBox) mExportview.findViewById(R.id.checkBox_1);
        radioButtonServer_2 = (CheckBox) mExportview.findViewById(R.id.checkBox_2);
        radioButtonServer_3 = (CheckBox) mExportview.findViewById(R.id.checkBox_3);


        buttonDownload = (Button) mExportview.findViewById(R.id.buttonDownload);
        buttonDeleteContac = (Button) mExportview.findViewById(R.id.buttonDeleteContact);
        ClearCountButton = (Button) mExportview.findViewById(R.id.ClearCountButton);
    }

    /**
     * 初始化监听
     */
    @Override
    public void initListener() {
        radioButtonServer1.setOnCheckedChangeListener(new CheckBox.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton arg0, boolean arg1) {
                radioButtonServer2.setChecked(false);
                radioButtonServer3.setChecked(false);
                radioButtonServer4.setChecked(false);
                radioButtonServer5.setChecked(false);
                radioButtonServer6.setChecked(false);
            }
        });

        radioButtonServer2.setOnCheckedChangeListener(new CheckBox.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton arg0, boolean arg1) {
                radioButtonServer1.setChecked(false);
                radioButtonServer3.setChecked(false);
                radioButtonServer4.setChecked(false);
                radioButtonServer5.setChecked(false);
                radioButtonServer6.setChecked(false);
            }
        });

        radioButtonServer3.setOnCheckedChangeListener(new CheckBox.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton arg0, boolean arg1) {
                radioButtonServer1.setChecked(false);
                radioButtonServer2.setChecked(false);
                radioButtonServer4.setChecked(false);
                radioButtonServer5.setChecked(false);
                radioButtonServer6.setChecked(false);
            }
        });

        radioButtonServer4.setOnCheckedChangeListener(new CheckBox.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton arg0, boolean arg1) {
                radioButtonServer1.setChecked(false);
                radioButtonServer2.setChecked(false);
                radioButtonServer3.setChecked(false);
                radioButtonServer5.setChecked(false);
                radioButtonServer6.setChecked(false);
            }
        });

        radioButtonServer5.setOnCheckedChangeListener(new CheckBox.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton arg0, boolean arg1) {
                radioButtonServer1.setChecked(false);
                radioButtonServer2.setChecked(false);
                radioButtonServer3.setChecked(false);
                radioButtonServer4.setChecked(false);
                radioButtonServer6.setChecked(false);
            }
        });

        radioButtonServer6.setOnCheckedChangeListener(new CheckBox.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton arg0, boolean arg1) {
                radioButtonServer1.setChecked(false);
                radioButtonServer2.setChecked(false);
                radioButtonServer3.setChecked(false);
                radioButtonServer4.setChecked(false);
                radioButtonServer5.setChecked(false);
            }
        });

        radioButtonServer_1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                radioButtonServer_2.setChecked(false);
                radioButtonServer_3.setChecked(false);
            }
        });
        radioButtonServer_2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                radioButtonServer_1.setChecked(false);
                radioButtonServer_3.setChecked(false);
            }
        });
        radioButtonServer_3.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                radioButtonServer_2.setChecked(false);
                radioButtonServer_1.setChecked(false);
            }
        });

        buttonDownload.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                int  code = isInformationComplete();
                if (code == 1){
                    Toast.makeText(context , "请输入信息，否则无法下载", Toast.LENGTH_SHORT).show();
                }else if (code == 2){
                    Toast.makeText(context, "请连接网络，（若已连接网络，请重启应用）", Toast.LENGTH_SHORT).show();
                }else if (code == 3){
                    Toast.makeText(context, "数据有误，请检查...", Toast.LENGTH_SHORT).show();
                }else if ( code == 0 ){
                    //上传
                    initLoadUi();
                    downloadContactOnHTTPV2();
                }
            }
        });
        buttonDeleteContac.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                deleteContacts();
            }
        });
        ClearCountButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                setDownloadedNumberToZero();
            }
        });
    }


    /**
     * 归零的监听
     */
    @Override
    public void setDownloadedNumberToZero() {
        TextView requestedContactNumber = (TextView) mExportview.findViewById(R.id.textViewRequestedContactNumber);
        requestedContactNumber.setText("0");
        TextView downloadedContactNumber = (TextView) mExportview.findViewById(R.id.textViewDownloadedContactNumber);
        downloadedContactNumber.setText("0");
    }

    @Override
    public void deleteContacts() {
        int contactCount =exportModel.getContactsCount();
        if (contactCount > 400) {
            exportModel.deleteAllContacts();
        } else {
            exportModel.deleteFewContacts();
        }
    }

    @Override
    public int isInformationComplete() {
        String selectedServerName = getSelectedServerName();
        if (TextUtils.isEmpty(selectedServerName)){
            return 3;
        }
        urlData =  getSelectedData();
        Log.e("TAG" , urlData);
        if (TextUtils.isEmpty(urlData)){
            return 3;
        }

        mLoadUrl = serverMapping.get(selectedServerName);
        // Get information
        EditText editTextContactNumber = (EditText) mExportview.findViewById(R.id.editTextContactNumber);
        String manualContactNumber = editTextContactNumber.getText().toString();
        contactNumber = manualContactNumber;
        EditText editTextUserName = (EditText) mExportview.findViewById(R.id.editTextUserName);
         userName = editTextUserName.getText().toString();
        EditText editTextPassword = (EditText)mExportview.findViewById(R.id.editTextPassword);
         password = editTextPassword.getText().toString();
        // Use Device Id to replace phoneNumber
         phoneNumber = getPhoneDeviceSerial();
        TextView textViewLocalIP = (TextView) mExportview.findViewById(R.id.localIPAddressTextView);
        localIPAddress = textViewLocalIP.getText().toString();
        if (TextUtils.isEmpty(userName) ||TextUtils.isEmpty(contactNumber) || TextUtils.isEmpty(password)  || TextUtils.isEmpty(phoneNumber) ) {
            return 1;
        }
        if (TextUtils.isEmpty(localIPAddress)) {
            return 2;
        }
        return 0;
    }


    //初始化上传UI
    @Override
    public void initLoadUi() {
        TextView requestedContactNumber = (TextView) mExportview.findViewById(R.id.textViewRequestedContactNumber);
        int downloadedNumber = Integer.parseInt(requestedContactNumber.getText().toString());
        downloadedNumber += Integer.parseInt(contactNumber);
        requestedContactNumber.setText(Integer.toString(downloadedNumber));
        progressDialog = ProgressDialog.show(context, "Loading...", "Please wait...", true, false);
        exportModel.saveInfoToSharePreferences(userName, contactNumber, password);
    }

    //下载联系人保存到本地
    @Override
    public void downloadContactOnHTTPV2() {
        exportModel.upload( mLoadUrl , userName , password , phoneNumber ,localIPAddress , contactNumber , urlData );
    }

    @Override
    public void onUploadCompleteUI() {
        ((Activity)context).runOnUiThread(new Runnable() {
            @Override
            public void run() {
                progressDialog.dismiss();
                TextView downloadedContactNumber = (TextView) mExportview.findViewById(R.id.textViewDownloadedContactNumber);
                int downloadedNumber = Integer.parseInt( downloadedContactNumber.getText().toString());
                downloadedNumber += importContactNumber;
                downloadedContactNumber.setText(Integer.toString(downloadedNumber));
                Toast.makeText(context, "已导入联系人数量: " + importContactNumber, Toast.LENGTH_SHORT).show();
            }
        });
    }


    private String getSelectedServerName() {
        if(radioButtonServer1.isChecked() ) {
            return radioButtonServer1.getText().toString();
        }
        if(radioButtonServer2.isChecked()) {
            return radioButtonServer2.getText().toString();
        }
        if(radioButtonServer3.isChecked()) {
            return radioButtonServer3.getText().toString();
        }
        if(radioButtonServer4.isChecked()) {
            return radioButtonServer4.getText().toString();
        }
        if(radioButtonServer5.isChecked()) {
            return radioButtonServer5.getText().toString();
        }
        if(radioButtonServer6.isChecked()) {
            return radioButtonServer6.getText().toString();
        }
        return null;
    }

    //获取数据来源
    private String getSelectedData() {
        if(radioButtonServer_1.isChecked()) {
            return "1";
        }
        if(radioButtonServer_2.isChecked()) {
            return "2";
        }
        if(radioButtonServer_3.isChecked()) {
            return "3";
        }
        return "";
    }


    @Override
    public void initEditText() {
        //初始化用户名
        String lastUserName = exportModel.getUserNameFromSharePreferences();
        EditText editTextUserName = (EditText) mExportview.findViewById(R.id.editTextUserName);
        editTextUserName.setText(lastUserName);
        //初始化密码
        String lastPassword = exportModel.getPasswordFromSharePreferences();
        EditText editTextPassword = (EditText) mExportview.findViewById(R.id.editTextPassword);
        editTextPassword.setText(lastPassword);
        //初始化ip
        String lastContactNumber = exportModel.getContactNumberFromSharePreferences();
        EditText editTextContactNumber = (EditText) mExportview.findViewById(R.id.editTextContactNumber);
        editTextContactNumber.setText(lastContactNumber);
    }


    @Override
    public void displayIPAndPhoneNumber() {
        TextView textViewIPAddress = (TextView) mExportview.findViewById(R.id.localIPAddressTextView);
        String localIPAddress = exportModel.getIPAddress();
        textViewIPAddress.setText(localIPAddress);
    }

    //存储信息
    public void setServerMapping() {
//        serverMapping.put("大有荣泰", "103.25.65.231:3011");
        serverMapping.put("乾坤信息", "10.9.4.21:8061");
//        serverMapping.put("大有荣亨", "10.1.0.231:8060");
//        serverMapping.put("大有荣成", "");
//        serverMapping.put("大有荣泰2", "10.20.0.152:3011");
        serverMapping.put("钱坤", "10.20.0.151:3010");
        serverMapping.put("钱坤投资", "10.10.0.14:8099");
        serverMapping.put("钱坤科技", "");
        serverMapping.put("曦昆", "180.169.122.30:3011");
    }

    /**
     * 返回序列号
     * @return
     */
    public String getPhoneDeviceSerial() {
        return exportModel.getPhoneDeviceSerial();
    }

    /**
     *上传失败的回掉
     */
    @Override
    public void onFailure() {
        ((Activity)context).runOnUiThread(new Runnable() {
            @Override
            public void run() {
                progressDialog.dismiss();
                Toast.makeText( context , "网络问题,请求失败", Toast.LENGTH_SHORT).show();
            }
        });
    }

    /**
     *上传成功的回掉
     */
    @TargetApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH_MR1)
    @Override
    public void uploadResponse( Response response ) {
        importContactNumber = 0;
        try {
            InputStream resultInputStream = response.body().byteStream();
            xmlPullParser(resultInputStream);
            exportModel.addManyContact(contactMap);
            onUploadCompleteUI();
        } catch (IOException e) {
            e.printStackTrace();
            Toast.makeText(context, "读写文件失败,请打开权限: " + importContactNumber , Toast.LENGTH_SHORT ).show();
        } catch (RemoteException e) {
            e.printStackTrace();
            Toast.makeText(context, "上传失败...: " + importContactNumber , Toast.LENGTH_SHORT ).show();
        } catch (OperationApplicationException e) {
            e.printStackTrace();
            Toast.makeText(context, "上传失败...: " + importContactNumber , Toast.LENGTH_SHORT ).show();
        }
    }

    /**
     * xml 解析
     * @param resultInputStream
     */
    @TargetApi(Build.VERSION_CODES.GINGERBREAD)
    public void xmlPullParser(InputStream resultInputStream)  {
        XmlPullParser parser = Xml.newPullParser();
         contactMap = new HashMap<>();
        int userCount = 0;
//        contactMap.put("User_" + 2 , "1878487851"+0);
//        contactMap.put("User_" + 3 , "1878487852"+1);
//        contactMap.put("User_" + 4 , "1878487853"+2);
//        contactMap.put("User_" + 5 , "1878487854"+3);
//        contactMap.put("User_" + 6 , "1878487855"+4);
//        contactMap.put("User_" + 7 , "1878487856"+5);
//        contactMap.put("User_" + 8 , "1878487857"+6);
//        contactMap.put("User_" + 9 , "1878487858"+7);
        try {
            parser.setInput(resultInputStream, "UTF-8");
            int eventType = parser.getEventType();
            while ( eventType != XmlPullParser.END_DOCUMENT ) {
                if ( eventType == XmlPullParser.START_TAG ) {
                    String tagName = parser.getName();
                    if (tagName.equalsIgnoreCase("Msg")) {
                        String msg = parser.nextText();
                        if (!msg.isEmpty()) {
                            errorMessage = msg;
                            ((Activity) context).runOnUiThread( new Runnable(){
                                @Override
                                public void run(){
                                    progressDialog.dismiss();
                                    Toast.makeText(context, errorMessage, Toast.LENGTH_SHORT).show();
                                }
                            });
                            return;
                        }
                    }
                } else if (eventType == XmlPullParser.TEXT) {
                    String text = parser.getText();
                    if (text.length() == 11) {
                        Log.e("TAG" , userCount + "---------->" + text);
                        contactMap.put("User_" + userCount , text);
                        userCount++;
                        importContactNumber++;
                    }
                }
                eventType = parser.next();
            }
        }catch (XmlPullParserException e){
            e.printStackTrace();
        }catch (IOException e){
            e.printStackTrace();
        }
    }

}
